﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using VerficationsWPF.Models;

namespace VerficationsWPF
{
    /// <summary>
    /// MainFrameWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainFrameWindow : Window
    {
        public MainFrameWindow()
        {
            InitializeComponent();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            lbList.Items.Clear();

            string nspace = "VerficationsWPF.Models";

            var types = from t in Assembly.GetExecutingAssembly().GetTypes()
                        where t.IsClass && t.Namespace == nspace
                        select t;

            // 通过LinQ进行排序，根据重要度，如果有就返回，否则返回0.
            var q1 = types.Where(t =>
            {
                if (Attribute.GetCustomAttribute(t, typeof(InfoAttribute)) is InfoAttribute iatt)
                    return iatt.IsDisplayed;
                return false;
            }).OrderBy(t => t.FullName).OrderByDescending(m =>
            {
                if (Attribute.GetCustomAttribute(m, typeof(InfoAttribute)) is InfoAttribute iatt)
                    return iatt.Importance;
                return 0;
            });

            // 添加到列表中
            foreach (var type in q1)
            {
                lbList.Items.Add(type);
            }

            if (lbList.Items.Count > 0)
                lbList.SelectedIndex = 0;
        }

        private void lbList_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            Debug.WriteLine(lbList.SelectedIndex);
            if (lbList.SelectedItem is Type t)
            {
                var control = Activator.CreateInstance(t);
                if (control is BaseModel bm)
                {
                    content.Child = bm;
                    lbTitle.Content = bm.Title;
                    lbDescirbe.Content = bm.Description;
                }
                else if (control is Window window)
                {
                    window.Owner = this;
                    window.WindowStartupLocation = WindowStartupLocation.CenterOwner;
                    window.ShowDialog();
                }
            }
            else
            {
                content.Child = null;
            }
        }
    }
}
